package com.project.nimsen.web.sys;

import java.io.File;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.project.nimsen.common.FileUpload;
import com.project.nimsen.entity.Fileinfo;
import com.project.nimsen.entity.User;
import com.project.nimsen.service.IFileinfoService;
import com.project.nimsen.util.FileVisitUtil;
import com.project.nimsen.util.WebUtil;
import com.project.jdbc.web.BaseMVCAction;
/**
 * 文件上传Control
 * */
@Controller
@RequestMapping(value ="/sys/file")
public class FileControl extends BaseMVCAction {
	@Resource
	WebUtil webUtil;
	@Resource
	IFileinfoService fileinfoService;
	@RequestMapping(value="/microimgupload")
	public void microimgupload(HttpServletRequest request,
		@RequestParam(value="microimg") MultipartFile uploadFile,
		HttpServletResponse response){
		try {
			response.getWriter().println(upload(uploadFile, request).toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
	}
	/**
	 * 上传方法
	 * */
	private JSONObject upload(MultipartFile uploadFile, HttpServletRequest request)throws Exception{
		String srcname = new String(uploadFile.getOriginalFilename().getBytes("ISO8859-1"),"UTF-8");
		FileUpload upload = FileVisitUtil.getFileUpload(uploadFile, request);
		upload.upload();
		String autoFilename = upload.getAutoFilename();
		Fileinfo finfo = new Fileinfo();
		finfo.setActive(0);
		finfo.setAutoname(autoFilename);
		finfo.setCreateTime(new Date());
		
		//当前登录人
		User use = webUtil.getCurrUser();
		
		finfo.setCreateUser(use.getId());  
		finfo.setFilename(upload.getRootPath()+File.separator+autoFilename);
		finfo.setFiletype(autoFilename.substring(autoFilename.lastIndexOf(".")+1));
		finfo.setSrcname(srcname);
		finfo.setUnzip(0);
		Object idobj = fileinfoService.save(finfo);
//		map.put("error", "0");
//		map.put("url", finfo.getFilename());
//		response.getWriter().println("{\"error\" : 0,\"url\" : \""+finfo.getFilename()+"\"}");
		JSONObject json = new JSONObject();
		if(idobj!=null)
			json.put("id", idobj.toString());
		json.put("error", 0);
		json.put("url", finfo.getFilename());
		return json;
	}
	
//	public Map<String, Object> kindeditorupload(HttpServletRequest request,
	//@ResponseBody
	@RequestMapping(value ="/kindeditorupload")
	public void kindeditorupload(HttpServletRequest request,
		@RequestParam(value="imgFile") MultipartFile uploadFile,
		HttpServletResponse response){
		//图片
//		key:localUrl--------value:null
//		key:dir--------value:image
//		key:imgFile
		//图片集合
//		key:dir--------value:image
//		key:Filename--------value:null
//		key:Upload--------value:null
		//flash文件上传
//		key:dir--------value:flash
		//视频文件上传
//		key:dir--------value:media
		//文件上传
//		key:dir--------value:file
		
//		System.out.println("kindeditorupload");
//		Map params = request.getParameterMap();
//		Set set = params.keySet();
//		Iterator i = set.iterator();
//		while(i.hasNext()){
//			Object obj = i.next();
//			System.out.println("key:"+obj.toString()+"--------value:"+getParameter(obj.toString()));
//		}
		
		try {
			response.getWriter().println(upload(uploadFile, request).toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
//		try{
//			
//			DefaultMultipartHttpServletRequest filereq = (DefaultMultipartHttpServletRequest)request;
//			Map<String, MultipartFile> fileMap = filereq.getFileMap();
//			Set<String> set = fileMap.keySet();
//			Iterator<String> i = set.iterator();
//			while(i.hasNext()){
//				System.out.println(i.next());
//			}
//			
//		}catch(Exception e){
//			e.printStackTrace();
//			logger.error(e);
//		}
//		return map;
	}
//	@ResponseBody
//	public Map<String, Object> kindeditormanager(HttpServletRequest request,
	@RequestMapping(value ="/kindeditormanager")
	public void kindeditormanager(HttpServletRequest request,
			HttpServletResponse response){
		return;
		
		/*
//		System.out.println("kindeditormanager");
//		Map params = request.getParameterMap();
//		Set set = params.keySet();
//		Iterator i = set.iterator();
//		while(i.hasNext()){
//			Object obj = i.next();
//			System.out.println("key:"+obj.toString()+"--------value:"+getParameter(obj.toString()));
//		}
		
//		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject map = new JSONObject();
		//网站根目录
//		ServletContext sevcon = request.getSession().getServletContext();
//		String rootPath = sevcon.getRealPath("");
		String current_url = "";
		try {
			List<Map<String, Object>> files = fileinfoService.findByDto(null);
			JSONArray rows = new JSONArray();
			if(CollectionUtils.isEmpty(files)){
				map.put("current_url", current_url+"/");
				map.put("moveup_dir_path", current_url+"/");
				map.put("current_dir_path", current_url+"/");
				map.put("total_count", 0);
				map.put("file_list", rows);
//				return map;
				response.getWriter().println(map.toString());
				return;
			}
			//处理查询出的数据
			for(Map<String, Object> fil : files){
				JSONObject row = new JSONObject();
				String filename = (String)fil.get("filename");
				current_url = filename.substring(0, filename.lastIndexOf("/"));
				String filetype = (String)fil.get("filetype");
				String autoname = (String)fil.get("autoname");
				Date createTime = (Date)fil.get("createTime");
				URL url = new URL(filename);
//				URI uri = new URI(filename);
				File file = new File(autoname);
				FileCopyUtils.copy(url.openStream(), new FileOutputStream(file));
				
				
				row.put("is_dir", false);
				row.put("has_file", false);
				row.put("filesize", file.length());
				row.put("is_photo", true);
				row.put("filetype", filetype);
				row.put("filename", autoname);
				row.put("datetime", DateUtils.convertDate2String(createTime));
				
				rows.add(row);
			} 
			
			map.put("file_list", rows);
			map.put("moveup_dir_path", current_url+"/");
			map.put("current_dir_path", current_url+"/");
			map.put("current_url", current_url+"/");
			response.getWriter().println(map.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
//		return map;
		return;
		*/
	}
}
